import { prisma } from '../../utils/prisma'
import { assertChildOwnership } from '../../utils/guard'
import { parseLocalDate } from '../../utils/date'
import { z } from 'zod'

const bodySchema = z.object({
  childId: z.number().int(),
  activityTemplateId: z.number().int(),
  date: z.string(), // YYYY-MM-DD
  quantity: z.number().int().min(1).default(1),
  note: z.string().optional()
})

export default eventHandler(async (event) => {
  const body = await readBody(event)
  const parsed = bodySchema.safeParse(body)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const { childId, activityTemplateId, date, quantity, note } = parsed.data
  await assertChildOwnership(event, childId)
  const tpl = await prisma.activityTemplate.findFirst({ where: { id: activityTemplateId } })
  if (!tpl) throw createError({ statusCode: 404, statusMessage: 'TEMPLATE_NOT_FOUND' })
  const points = tpl.pointsPerUnit * quantity
  const recordDate = parseLocalDate(date)

  const record = await prisma.$transaction(async (tx) => {
    const r = await tx.activityRecord.create({
      data: { childId, activityTemplateId, date: recordDate, quantity, points, note }
    })
    await tx.pointsLedger.create({
      data: {
        childId,
        kind: points >= 0 ? 'earn' : 'spend',
        amount: Math.abs(points),
        sourceType: 'activity',
        sourceId: r.id,
        occurredAt: recordDate  // 使用记录的日期作为发生时间
      }
    })
    return r
  })

  return { record }
})


